<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>启动页</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            position: relative;
        }
        /* 状态栏 */
        .status-bar {
            background-color: #1DBF7B;
            color: white;
            width: 100%;
            height: 5.5rem; /* 标准状态栏高度 */
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }

        .time {
            color: white;
            font-size: 1rem;
            font-weight: 500;
            position:absolute;
            top:1.6%;
            left:5.3%;
        }

        /* 主要内容容器 */
        .logo-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 1rem; 
        }

        /* Logo 图片（保持宽高比） */
        .logo  {
            background-size: contain;
            position:fixed;
            background-repeat: no-repeat;
            background-position: center;
            top:28%;
            left:8.5%;
            width:82.9%;
            height:23.6%;
            margin-bottom: 8.8%;
            object-fit: cover;
            max-width:100%;
            aspect-ratio: auto; 
        }
        /* 按钮样式 */
        .button {
            background-color: #1DBF7B;
            border-radius: 30px;
            width: 66%; /* 相对宽度 */
            position:fixed;
            padding: 1rem 0;
            display: flex;
            top:60.5vh;
            
            justify-content: center;
            color: rgb(255, 255, 255);
            font-size: 1rem;
            font-weight: bold;
            text-decoration: none;
            margin-top: 1.5rem;
        }

        /* 加载状态样式 */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        
    </style>
</head>
<body>
    <div class="status-bar">
        <div class="time">9:41</div>
    </div>
    
    <div class="logo-container">
        
            <img src ="./images/index_image_1.png" class = "logo">
        
        <a href="javascript:void(0)" class="button" id="loginBtn">打开学都会</a>
    </div>

    <script>
        // 配置常量
        const API_CONFIG = {
            // 后端接口基础URL
            BASE_URL: 'http://localhost:8080/api',
            // 登录接口
            LOGIN_URL: '/auth/login',
            // 用户信息接口
            USER_INFO_URL: '/user/info',
            // 模拟openid
            MOCK_OPENID: 'mock_openid_123456789'
        };

        // 用户状态管理
        const UserState = {
            isLoggedIn: false,
            openid: null,
            userInfo: null,
            token: null
        };

        // 工具函数：显示提示信息
        function showMessage(message, type = 'info') {
            console.log(`[${type.toUpperCase()}] ${message}`);
            // 可以在这里添加UI提示，比如toast组件
        }

        // 工具函数：生成随机openid
        function generateMockOpenid() {
            const timestamp = Date.now();
            const random = Math.random().toString(36).substring(2, 15);
            return `mock_openid_${timestamp}_${random}`;
        }

        // 工具函数：模拟网络延迟
        function delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        // 模拟获取openid（实际项目中可能从微信、支付宝等平台获取）
        async function getOpenid() {
            try {
                showMessage('正在获取用户身份信息...', 'info');
                
                // 模拟网络请求延迟
                await delay(1000);
                
                // 模拟从本地存储或第三方平台获取openid
                let openid = localStorage.getItem('user_openid');
                
                if (!openid) {
                    // 如果没有缓存的openid，生成一个新的
                    openid = generateMockOpenid();
                    localStorage.setItem('user_openid', openid);
                    showMessage('已生成新的用户身份标识', 'success');
                } else {
                    showMessage('已获取缓存的用户身份标识', 'success');
                }
                
                return openid;
            } catch (error) {
                showMessage('获取用户身份信息失败', 'error');
                throw error;
            }
        }

        // 模拟登录请求
        async function loginWithOpenid(openid) {
            try {
                showMessage('正在验证用户身份...', 'info');
                
                // 模拟网络请求延迟
                await delay(1500);
                
                // 模拟后端登录接口请求
                const loginData = {
                    openid: openid,
                    timestamp: Date.now(),
                    device: 'web'
                };
                
                // 模拟API请求
                const response = await mockApiRequest(API_CONFIG.LOGIN_URL, {
                    method: 'POST',
                    body: JSON.stringify(loginData)
                });
                
                if (response.success) {
                    UserState.isLoggedIn = true;
                    UserState.openid = openid;
                    UserState.token = response.data.token;
                    UserState.userInfo = response.data.userInfo;
                    
                    // 保存登录状态到本地存储
                    localStorage.setItem('user_token', response.data.token);
                    localStorage.setItem('user_info', JSON.stringify(response.data.userInfo));
                    
                    showMessage('登录成功', 'success');
                    return response.data;
                } else {
                    throw new Error(response.message || '登录失败');
                }
            } catch (error) {
                showMessage(`登录失败: ${error.message}`, 'error');
                throw error;
            }
        }

        // 模拟获取用户信息
        async function getUserInfo(openid) {
            try {
                showMessage('正在获取用户信息...', 'info');
                
                // 模拟网络请求延迟
                await delay(800);
                
                // 模拟API请求
                const response = await mockApiRequest(`${API_CONFIG.USER_INFO_URL}?openid=${openid}`, {
                    method: 'GET'
                });
                
                if (response.success) {
                    UserState.userInfo = response.data;
                    showMessage('用户信息获取成功', 'success');
                    return response.data;
                } else {
                    throw new Error(response.message || '获取用户信息失败');
                }
            } catch (error) {
                showMessage(`获取用户信息失败: ${error.message}`, 'error');
                throw error;
            }
        }

        // 模拟API请求函数
        async function mockApiRequest(url, options = {}) {
            // 模拟网络错误
            if (Math.random() < 0.1) {
                throw new Error('网络连接失败');
            }
            
            // 模拟不同的API响应
            if (url.includes('/auth/login')) {
                return {
                    success: true,
                    data: {
                        token: 'mock_token_' + Date.now(),
                        userInfo: {
                            id: 1,
                            openid: options.body ? JSON.parse(options.body).openid : API_CONFIG.MOCK_OPENID,
                            nickname: '测试用户',
                            avatar: 'http://gips3.baidu.com/it/u=3886271102,3123389489&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960',
                            email: 'test@example.com',
                            phone: '138****8888'
                        }
                    },
                    message: '登录成功'
                };
            } else if (url.includes('/user/info')) {
                return {
                    success: true,
                    data: {
                        id: 1,
                        openid: url.split('openid=')[1] || API_CONFIG.MOCK_OPENID,
                        nickname: '苟娅琳',
                        avatar: 'http://gips3.baidu.com/it/u=3886271102,3123389489&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960',
                        email: 'gouyalin@example.com',
                        phone: '138****8888',
                        studyProgress: {
                            totalQuestions: 1250,
                            completedQuestions: 856,
                            accuracy: 0.78
                        }
                    },
                    message: '获取用户信息成功'
                };
            }
            
            // 默认响应
            return {
                success: false,
                message: '未知接口'
            };
        }

        // 主登录流程
        async function handleLogin() {
            const loginBtn = document.getElementById('loginBtn');
            
            try {
                // 添加加载状态
                loginBtn.classList.add('loading');
                loginBtn.textContent = '正在登录...';
                
                // 1. 获取openid
                const openid = await getOpenid();
                
                // 2. 使用openid登录
                const loginResult = await loginWithOpenid(openid);
                
                // 3. 获取用户详细信息
                const userInfo = await getUserInfo(openid);
                
                // 4. 登录成功，跳转到首页
                showMessage('登录成功，正在跳转...', 'success');
                await delay(500);
                
                // 跳转到首页，携带用户信息
                window.location.href = `index.html?openid=${openid}&token=${loginResult.token}`;
                
            } catch (error) {
                showMessage(`登录流程失败: ${error.message}`, 'error');
                
                // 恢复按钮状态
                loginBtn.classList.remove('loading');
                loginBtn.textContent = '打开学都会';
            }
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定登录按钮点击事件
            document.getElementById('loginBtn').addEventListener('click', handleLogin);
            
            // 检查是否已经登录
            const token = localStorage.getItem('user_token');
            if (token) {
                showMessage('检测到已登录状态', 'info');
            }
            
            // 更新时间显示
            updateTime();
            setInterval(updateTime, 60000); // 每分钟更新一次
        });

        // 更新时间显示
        function updateTime() {
            const now = new Date();
            const timeString = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
            document.querySelector('.time').textContent = timeString;
        }

        // 导出用户状态，供其他页面使用
        window.UserState = UserState;
        window.API_CONFIG = API_CONFIG;
    </script>
</body>
</html>